#include <stdio.h>
#include <unistd.h>

#include "ohos_init.h"
#include "cmsis_os2.h"

#include "lwip/sockets.h"
#include "wifi_connect.h"

#define UDP_PROT 8888

//在sock_fd 进行监听
int sock_fd;

char recvbuf[512];
char *buf = "Hello! I'm BearPi-HM_Nano UDP Server!";

static void UDPServerTask(void)
{
	//服务端地址信息
	struct sockaddr_in server_sock;

	//客户端地址信息
	struct sockaddr_in client_sock;
	int sin_size;

	//连接Wifi
	WifiConnect("TEST", "12345678");

	//创建socket
	if ((sock_fd = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
	{
		perror("socket is error\r\n");
		exit(1);
	}

	bzero(&server_sock, sizeof(server_sock));
	server_sock.sin_family = AF_INET;
	server_sock.sin_addr.s_addr = htonl(INADDR_ANY);
	server_sock.sin_port = htons(UDP_PROT);

	//调用bind函数绑定socket和地址
	if (bind(sock_fd, (struct sockaddr *)&server_sock, sizeof(struct sockaddr)) == -1)
	{
		perror("bind is error\r\n");
		exit(1);
	}

	//处理目标
	ssize_t ret;
	while (1)
	{
		sin_size = sizeof(struct sockaddr_in);
		bzero(recvbuf, sizeof(recvbuf));
		if ((ret = recvfrom(sock_fd, recvbuf, sizeof(recvbuf), 0, (struct sockaddr *)&client_sock, (socklen_t *)&sin_size)) == -1)
		{
			perror("recv error\r\n");
		}
		printf("recv:%s\r\n", recvbuf);

		if ((ret = sendto(sock_fd, buf, strlen(buf), 0, (struct sockaddr *)&client_sock, sizeof(client_sock))) == -1)
		{
			perror("sned :");
		}
	}
}

static void UDPServerDemo(void)
{
	osThreadAttr_t attr;

	attr.name = "UDPServerTask";
	attr.attr_bits = 0U;
	attr.cb_mem = NULL;
	attr.cb_size = 0U;
	attr.stack_mem = NULL;
	attr.stack_size = 10240;
	attr.priority = osPriorityNormal;

	if (osThreadNew((osThreadFunc_t)UDPServerTask, NULL, &attr) == NULL)
	{
		printf("[UDPServerDemo] Falied to create UDPServerTask!\n");
	}
}

APP_FEATURE_INIT(UDPServerDemo);
